package cn.com.ebidding.dianjian.server.tasks;

import cn.com.ebidding.dianjian.server.dao.MongodbDao;
import cn.com.ebidding.dianjian.server.entity.DianJianInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by sehuaqi on 2017/7/6.
 */
@Component
@EnableScheduling
public class DianJianTask {

    private static final Logger log = LoggerFactory.getLogger(DianJianTask.class);

    private static int count = 0;
    private static Date lastPostTime = null;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Autowired
    private MongodbDao mongodbDao;

    private static final SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static String msg = null;

    @Scheduled(fixedRate = 3000)
    public void reportCurrentTime() {
        String url = "https://zcjb.com.cn/cms/check.htm?r="+Math.random();
        log.info("点检系统：" + url);
        DianJianInfo dianJianInfo = null;
        try {
            long responseTime = System.currentTimeMillis();
            String r = restTemplate.getForObject(url, String.class);
            responseTime = System.currentTimeMillis() - responseTime;
            dianJianInfo = new DianJianInfo(url, new Date(), "1", r, responseTime);
            log.info("点检结果：" + r);
        } catch (ResourceAccessException e) {
            log.info("错误信息：" + e.getMessage());
            dianJianInfo = new DianJianInfo(url, new Date(), "0", e.getMessage(), -30);
        } catch (Exception e) {
            log.info("这个异常有点可怕了：" + e.getMessage());
            dianJianInfo = new DianJianInfo(url, new Date(), "-1", e.getMessage(), -60);
        }
        mongodbDao.save(dianJianInfo);
    }

    @Scheduled(fixedRate = 10000)
    public void dataStatistics() {
        log.info("数据分析：");

        int pageSize = 10;
        PageRequest pageRequest = buildPageRequest(1, pageSize, Sort.Direction.DESC, "createTime");

        Page<DianJianInfo> dianJianInfos = mongodbDao.findAll(pageRequest);

        long countResponseTime = 0L;
        for (DianJianInfo d : dianJianInfos) {
            long responseTime = d.responseTime;
            countResponseTime += responseTime;
        }

        long avgResponseTime = countResponseTime / pageSize;

        if (avgResponseTime > 5000) {
            msg = "----->系统响应有点慢哦，平均响应时间为：" + avgResponseTime + "毫秒";
            log.info(msg);
            sendNotice("【招采进宝平台】有点慢", msg);
        } else if (avgResponseTime < -29) {
            msg = "----->系统出问题了，估计挂了countResponseTime=" + countResponseTime + "，avgResponseTime=" + avgResponseTime;
            log.info(msg);
            for (DianJianInfo d : dianJianInfos) {
                long responseTime = d.responseTime;
                log.info("----->最近30秒的响应时间分别为：" + d.responseTime + "毫秒");
            }
            sendNotice("【招采进宝平台】可能挂了", msg);
        } else {
            //应该是正常的哦
            if (lastPostTime != null && count != 0) {
                count = 0;
                lastPostTime = null;
                msg = "----->应用恢复正常";
                log.info(msg);
                sendNotice("【招采进宝平台】已恢复正常", msg);
            } else {
                log.info("----->应用运行正常，平均响应时间：" + avgResponseTime + "毫秒");
            }
        }
    }


    public void sendNotice(String title, String msg) {
        if (lastPostTime == null) {
            lastPostTime = new Date();
            sendEmail(title, msg);
        } else {
            Date currentDate = new Date();
            long cha = currentDate.getTime() - lastPostTime.getTime();
            double pow = Math.pow(60, count) * 1000;
            log.info("cha = " + cha + ", pow = " + pow);
            if (cha > pow) {
                sendEmail(title, msg);
            }
        }
    }

    /*@Async*/
    public void sendEmail(String title, String conent) {
        count++;
        log.info("----->发邮件通知");

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        // 设置收件人，寄件人
        simpleMailMessage.setTo(new String[]{"qiyang@ebidding.com.cn"});
        simpleMailMessage.setFrom("qiyang318@163.com");
        simpleMailMessage.setSubject(title);
        simpleMailMessage.setText(conent + "；服务器时间：" + dateFormate.format(new Date()));
        // 发送邮件
        mailSender.send(simpleMailMessage);

    }

    private PageRequest buildPageRequest(int pageNo, int pageSize, Sort.Direction softType, String sortFiled) {
        Sort sort = null;
        if (StringUtils.isEmpty(softType) || "auto".equals(softType)) {
            sort = new Sort(Sort.Direction.DESC, "id");
        } else {
            sort = new Sort(softType, sortFiled);
        }
        return new PageRequest(pageNo - 1, pageSize, sort);
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }
}
